﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using DAL;
using BLL;

namespace CTRL
{
    public sealed class CtrlBatteryStation
    {
        private static volatile CtrlBatteryStation instance;
        private static object syncRoot = new Object();

        private IDALBatteryCenter batteryCenterRepository;

        public CtrlBatteryStation()
        {
            this.batteryCenterRepository = new DALBatteryCenter(new CarBatteryEntities());
        }

        public static CtrlBatteryStation Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new CtrlBatteryStation();
                    }
                }
                return instance;
            }
        }

        public int CreateBatteryStation(string stName, System.TimeSpan stTimeOpen, System.TimeSpan stTimeClose)
        {
            BatteryStation batStat = new BatteryStation()
            {
                name = stName,
                timeOpen = stTimeOpen,
                timeClose = stTimeClose,
            };

            batteryCenterRepository.InsertBatteryStation(batStat);

            return batteryCenterRepository.Save();
        }

        public int UpdateBatteryStation(int ID, string stName, System.TimeSpan stTimeOpen, System.TimeSpan stTimeClose)
        {
            BatteryStation batStat = new BatteryStation()
            {
                stationID = ID,
                name = stName,
                timeOpen = stTimeOpen,
                timeClose = stTimeClose,
            };

            batteryCenterRepository.UpdateBatteryStation(batStat);

            return batteryCenterRepository.Save();
        }

        public int DeleteBatteryStation(string name)
        {
            BatteryStation batStat = FindBatteryCenter(name);

            if (batStat != null)
                batteryCenterRepository.DeleteBatteryStation(batStat.stationID);

            return batteryCenterRepository.Save();
        }

        public BatteryCenter FindBatteryCenter(string name)
        {
            BatteryStation b = batteryCenterRepository.FindBatteryStation(name);

            return b != null ? new BatteryCenter { name = b.name, stationID = b.stationID, timeOpen = b.timeOpen, timeClose = b.timeClose } : null;
        }

        public BatteryStation GetBatteryStationByID(int ID)
        {
            BatteryStation bs = batteryCenterRepository.GetBatteryStationByID(ID);

            return bs ?? null;
        }

        public IEnumerable<BatteryStation> GetAllStations()
        {
            return batteryCenterRepository.GetAllStations();
        }
    }
}